package com.example.reagent_management.ui.activity

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.lib_base.utils.MMKVUtils
import com.example.reagent_management.ui.activity.pojo.RemindDateAndCount
import com.example.reagent_management.ui.message.pojo.MessageRepository
import com.example.reagent_management.ui.operatedialog.repository.HistoryRepository
import com.example.reagent_management.ui.operatedialog.repository.StoreRepository
import com.example.reagent_management.ui.setting.COUNT_REMIND
import com.example.reagent_management.ui.setting.DAY__REMIND
import com.kunminx.architecture.ui.callback.UnPeekLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import javax.inject.Inject

@HiltViewModel
class MainActivityModel @Inject constructor(
    private val storeRepository: StoreRepository,
    private val messageRepository: MessageRepository
) :
    ViewModel() {

    val remindInfoList = UnPeekLiveData<List<RemindDateAndCount>>()

    fun setReminds(): Job {
        val job = viewModelScope.launch(Dispatchers.IO) {
            storeRepository.getRemindInfo()
                .collectLatest { list ->
                    delay(100)
                    val day = MMKVUtils.getHelper().decodeInt(DAY__REMIND, 1)
                    val count = MMKVUtils.getHelper().decodeInt(COUNT_REMIND, 1)
                    val thisTime = System.currentTimeMillis()
                    list.filter {
                        //过滤 (没过期且剩余日期小于等于提醒数)或 入库数num小于提醒数   两个都要提醒所以用 ||
                        (it.remindDay >= thisTime && it.remindDay - thisTime <= day * 86400000) || it.remindCount <= count
                    }
                    remindInfoList.postValue(list)
                }
        }
        return job
    }

    suspend fun hasRemind(type: Int, remindId: Long): Boolean {
        val result = messageRepository.getRemind(type, remindId)
        return result != -1L
    }
}